package com.qf.servlet;

import com.qf.model.User;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/list")

public class ListServlet extends HttpServlet {
    UserServiceImpl userService = new UserServiceImpl();
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");


        if ( username!=null){
            // 展现全部数据,再查询全部数据
            ArrayList<User> userList =userService.findAll();
            // 设置编码格式防止乱码
            // resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            // 向外展示数据
            out.write("<html>");
            out.write("<head>");
            out.write("<title>主页</title>");
            out.write("</head>");
            out.write("<body>");

            // TODO: 暂时这里无法获取user对象,后续讲完请求域再解决
            out.write("<h1>登录成功,欢迎"+username+"</h1>");
            out.write("<hr>");
            out.write("<button>");
            out.write("<a href = '/logout'>退出</a>");
            out.write("</button>");
            out.write("<h2>展现全部数据</h2>");
            out.write("<table border='2'>");
            out.write("<tr>");
            out.write(" <td>编号</td>");
            out.write(" <td>用户名</td>");
            out.write(" <td>密码</td>");
            out.write(" <td>性别</td>");
            out.write(" <td>时间</td>");
            out.write(" <td>手机号</td>");
            out.write("</tr>");
            for (User u : userList) {
                out.write("<tr>");
                out.write(" <td>"+u.getId()+"</td>");
                out.write(" <td>"+u.getUsername()+"</td>");
                out.write(" <td>"+u.getPassword()+"</td>");
                out.write(" <td>"+(u.getSex() == 1? "男" : "女")+"</td>");
                out.write(" <td>"+u.getCreateTime()+"</td>");
                out.write(" <td>"+u.getPhone()+"</td>");
                out.write("</tr>");
            }
            out.write("");
            out.write("</table>");
            out.write("</body>");
            out.write("</html>");
        }
        }


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

